<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :draggable="true">
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="所属楼栋" prop="buildingId">
        <el-input v-model="formData.buildingName" disabled />
      </el-form-item>
      <el-form-item label="房间号" prop="roomNumber">
        <el-input v-model="formData.roomNumber" placeholder="请输入房间号" />
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input v-model.number="formData.floor" placeholder="请输入楼层" type="number" min="1" />
      </el-form-item>
      <el-form-item label="套内面积" prop="area">
        <el-input v-model.number="formData.area" placeholder="请输入套内面积" type="number" min="0" />
        <template #append>㎡</template>
      </el-form-item>
      <el-form-item label="物业面积" prop="area">
        <el-input v-model.number="formData.propertyArea" placeholder="请输入套内面积" type="number" min="0" />
        <template #append>㎡</template>
      </el-form-item>
      <el-form-item label="房间状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择房间状态">
          <el-option label="空闲" value="idle" />
          <el-option label="已占用" value="occupied" />
          <el-option label="维护中" value="maintenance" />
        </el-select>
      </el-form-item>
      <el-form-item label="房间描述">
        <el-input v-model="formData.description" placeholder="请输入房间描述" type="textarea" :rows="4" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, inject } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import request from '@/api/request'

// 状态管理
const dialogVisible = ref(false);
const dialogTitle = ref('新增房间');
const formData = ref({});
const formRef = ref(null);

const maxFloors = ref(null)

// 验证规则
const rules = ref({
  roomNumber: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  floor: [
    { required: true, message: '请输入楼层', trigger: 'blur' },
    { type: 'number', min: 1, message: '楼层必须大于0', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入套内面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '套内面积必须大于等于0且小于8', trigger: 'blur' }
  ],
  propertyArea: [
    { required: true, message: '请输入物业面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '物业面积必须大于等于0且小于8', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择房间状态', trigger: 'change' }]
});

// 注入主组件的数据
const roomData = inject('roomData');
const emit = defineEmits(['success']);
let submitSuccessCallback = null

// 打开弹窗
const open = (data, callback) => {
  maxFloors.value = data.buildingFloors
  submitSuccessCallback = callback
  if (data.id) {
    // 编辑模式
    formData.value = { ...data };
    dialogTitle.value = '编辑房间';
  } else {
    // 新增模式
    formData.value = {
      ...data,
      roomNumber: '',
      floor: 1,
      area: 0,
      propertyArea: 0,
      status: 'idle',
      description: ''
    };
    dialogTitle.value = '新增房间';
  }
  dialogVisible.value = true;
};
// 保存数据
const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {


      let defaultFloors = maxFloors.value
      let floor = formData.value.floor

      if (defaultFloors < floor) {
        ElMessage.error("楼栋的最大层数为：" + defaultFloors + "；输入楼层数为" + floor)
        return
      }


      const loading = ElLoading.service({
        lock: true,
        text: '正在处理...',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      if (formData.value.id) {
        // 编辑
        request.post('/parkRoom/modify', formData.value).then(data => {
          dialogVisible.value = false;
          loading.close()
          if (data.success) {
            ElMessage.success(data.message);
            emit('success');
            // 提交成功后调用上层传入的回调
            if (submitSuccessCallback) {
              submitSuccessCallback("parkRoomList", formData.value.buildingId);
            }
          } else {
            ElMessage.success(data.message);
            emit('fail');
          }
        }).catch(error => {
          loading.close()
          ElMessage.error('编辑异常', error)
        });
      } else {
        // 新增
        request.post('/parkRoom/add', formData.value).then(data => {
          dialogVisible.value = false;
          loading.close()
          if (data.success) {
            ElMessage.success(data.message);
            emit('success');
            // 提交成功后调用上层传入的回调
            if (submitSuccessCallback) {
              submitSuccessCallback("parkRoomList", formData.value.buildingId);
            }
          } else {
            ElMessage.success(data.message);
            emit('fail');
          }
        }).catch(error => {
          loading.close()
          ElMessage.error('编辑异常', error)
        });
      }

    }
  });
};

// 暴露方法
defineExpose({
  open
});
</script>
